package com.ruiao.tools.dongtaiguankong;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ruiao.tools.R;
import com.ruiao.tools.bean.DongtaiGuankongNowDataBean;
import com.ruiao.tools.dongtaiguankong.histroy.DongtaiFenActivity;
import com.ruiao.tools.dongtaiguankong.histroy.DongtaiTianActivity;
import com.ruiao.tools.dongtaiguankong.histroy.DongtaiZhouActivity;
import com.ruiao.tools.ic_card2.DevBean;
import com.ruiao.tools.ic_card2.FactroyBean;
import com.ruiao.tools.ui.adapter.DongTaiNowDataAdapter;
import com.ruiao.tools.url.URLConstants;
import com.ruiao.tools.utils.AsynHttpTools;
import com.ruiao.tools.utils.SPUtils;
import com.ruiao.tools.utils.ToastHelper;
import com.ruiao.tools.widget.Pbdialog;

import cz.msebera.android.httpclient.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class DongtaiLishi extends Fragment implements RadioGroup.OnCheckedChangeListener {
    @BindView(R.id.rb_cod)
    RadioButton rbCod;
    @BindView(R.id.rb_andan)
    RadioButton rbAndan;
    @BindView(R.id.rb_ph)
    RadioButton rbPh;
    @BindView(R.id.rb_zongdan)
    RadioButton rbZongdan;
    @BindView(R.id.rg)
    RadioGroup rg;
    @BindView(R.id.sb_type_one)
    TextView sbTypeOne;
    @BindView(R.id.sb_nowdata)
    TextView sbNowdata;
    @BindView(R.id.sb_type_two)
    TextView sbTypeTwo;
    @BindView(R.id.sb_status)
    TextView sbStatus;
    @BindView(R.id.sb_type_three)
    TextView sbTypeThree;
    @BindView(R.id.sb_waring)
    TextView sbWaring;
    @BindView(R.id.rv_parms)
    RecyclerView rvParms;
    @BindView(R.id.rb_liuliang)
    RadioButton rbLiuliang;
    @BindView(R.id.rb_zonglin)
    RadioButton rbZonglin;
    private String MonitorID = null;
    ArrayList<String> fac_list = new ArrayList<>();
    ArrayList<ArrayList<String>> dev_list = new ArrayList<>();
    private ArrayAdapter<String> adapter;
    private ArrayAdapter<String> dev_adapter;
    private boolean isDataReady = false;
    private boolean ready = false;
    ArrayList<FactroyBean> little = new ArrayList<>();
    Unbinder unbinder;
    Date nowTime = new Date();
    DateFormat bf = new SimpleDateFormat("MM月dd日HH时mm分");
    @BindView(R.id.tv_newDate)
    TextView facName;
    private Pbdialog dialog; //进度条

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    ArrayList<ArrayList<DevBean>> biglist = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_guankong_lishi,
                container, false);
        unbinder = ButterKnife.bind(this, view);
        rg.setOnCheckedChangeListener(this);
        dataAdapter = new DongTaiNowDataAdapter(getActivity());
        rvParms.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvParms.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL));
        rvParms.setAdapter(dataAdapter);
        initView();
        return view;
    }

    private void initView() {
        initFacDev();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

    }

    @OnClick({R.id.ll_shifenzhong, R.id.ll_xiaoshi, R.id.ll_zhou, R.id.ll_select_dev})
    public void onViewClicked(View view) {
        if (!isDataReady) {
            ToastHelper.shortToast(getContext(), "请先选择企业");
            return;
        }
        switch (view.getId()) {
            case R.id.ll_shifenzhong:
                Intent intent1 = new Intent(getContext(), DongtaiFenActivity.class);
                intent1.putExtra("MonitorID", MonitorID);
                startActivity(intent1);
                break;
            case R.id.ll_xiaoshi:
                Intent intent2 = new Intent(getContext(), DongtaiTianActivity.class);
                intent2.putExtra("MonitorID", MonitorID);
                startActivity(intent2);
                break;
            case R.id.ll_zhou:
                Intent intent3 = new Intent(getContext(), DongtaiZhouActivity.class);
                intent3.putExtra("MonitorID", MonitorID);
                startActivity(intent3);
                break;
            case R.id.ll_select_dev:
                initFacDev();
                break;
        }
    }

    public Pbdialog showdialog(Context context, String msg) {
        Pbdialog pbdialog = new Pbdialog(context);
        pbdialog.setMessage(msg);
        pbdialog.show();
        return pbdialog;
    }

    private void initFacDev() {
        dialog = showdialog(getContext(), "正在加载.......");
        RequestParams pa = new RequestParams();
        adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1,
                fac_list);
        pa.add("username", (String) SPUtils.get(getContext(), "username", ""));
//        AsynHttpTools.httpGetMethodByParams(URLConstants.GONGDI_FAC, pa, new
//        JsonHttpResponseHandler("GB2312") {
        AsynHttpTools.httpGetMethodByParams(URLConstants.Dongtai_FAC, pa,
                new JsonHttpResponseHandler("GB2312") {
                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }

                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString,
                                          Throwable throwable) {
                        throwable.printStackTrace();
                    }

                    @Override
                    public void onFailure(int code, Header[] heads, Throwable throwable,
                                          JSONObject json) {

                        throwable.printStackTrace();

                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        fac_list.clear();
                        try {
                            Boolean status = response.getBoolean("success");
                            if (status) {
                                JSONArray arr = response.getJSONArray("factory");
                                JSONObject fac = null;
                                JSONArray devs = null;
                                JSONObject dev = null;
                                for (int i = 0; i < arr.length(); i++) {
                                    fac = arr.getJSONObject(i);
                                    String facname = fac.getString("name"); //工厂名字

                                    fac_list.add("" + i + " " + facname);

                                    little.add(new FactroyBean(facname));
                                    devs = fac.getJSONArray("device");

                                    ArrayList<String> temp = new ArrayList<>();
                                    ArrayList<DevBean> mlist = new ArrayList<>();
                                    for (int j = 0; j < devs.length(); j++) {
                                        dev = devs.getJSONObject(j);
                                        String devNane = dev.getString("name");
                                        String devId = dev.getString("id");

                                        mlist.add(new DevBean(devNane, devId));

                                        temp.add(devNane);
                                    }
                                    dev_list.add(temp);
                                    biglist.add(mlist);
                                }
                                ready = true;
                                initPickerView();

                            } else {
                                ToastHelper.shortToast(getContext(), response.getString("message"));

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void initPickerView() {
        if (!ready) {
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setIcon(R.mipmap.ic_lonch);
        builder.setTitle("选择企业：");
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
//                Toast.makeText(MainActivity.this, "你点击了第"+which+"个item", 1000).show();;
                showDev(which);
            }
        });
        builder.show();
    }

    public void showDev(final int bwhich) {
        dev_adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1,
                dev_list.get(bwhich));
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setIcon(R.mipmap.ic_lonch);
        builder.setTitle("选择设备：");
        builder.setAdapter(dev_adapter, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                String id = biglist.get(bwhich).get(which).getId(); //获取设备ID
                MonitorID = id;
//                facName.setText(little.get(bwhich).getFacname());
                facName.setText(little.get(bwhich).getFacname() + biglist.get(bwhich).get(which).getDevNane());
//                MonitorID = MonitorID;
                isDataReady = true;
                initData(id);
            }
        });
        builder.show();
    }

    DongtaiGuankongNowDataBean data;
    DongTaiNowDataAdapter dataAdapter;

    private void initData(String MonitorID) {
        dialog = showdialog(getContext(), "正在加载.......");
        RequestParams pa = new RequestParams();
        //pa.add("start", format.format(new Date(nowTime.getTime() - 5 * 60 * 1000)));
        //pa.add("end", format.format(nowTime));
        //pa.add("ActType", "1");
        pa.add("MonitorID", MonitorID);
        //pa.add("username", (String) SPUtils.get(getContext(), "username", ""));
        AsynHttpTools.httpGetMethodByParams(URLConstants.dongtaiguankong_nowdata, pa,
                new JsonHttpResponseHandler("GB2312") {
                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onFailure(int code, Header[] heads, Throwable throwable,
                                          JSONObject json) {
                        throwable.printStackTrace();
                        ToastHelper.shortToast(getContext(), throwable.getMessage());
                    }

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            DongtaiGuankongNowDataBean bean =
                                    new Gson().fromJson(response.toString(),
                                            DongtaiGuankongNowDataBean.class);
                            if (bean.isSuccess()) {
                                data = bean;
                                rbLiuliang.setChecked(true);
                            } else {
                                data = null;
                                ToastHelper.shortToast(getContext(), bean.getMessage().toString());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                });
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (data != null) {
            switch (checkedId) {
                case R.id.rb_liuliang:
                    rvParms.setVisibility(View.GONE);
                    dataAdapter.setData(data.getData(), 1);
                    sbTypeOne.setText(data.getData().get流量().getNowdata().getName());
                    sbNowdata.setText(data.getData().get流量().getNowdata().getValue());
                    sbTypeTwo.setText(data.getData().get流量().getDrivestaus().getName());
                    sbStatus.setText(data.getData().get流量().getDrivestaus().getValue());
                    sbTypeThree.setText(data.getData().get流量().getWaringstatus().getName());
                    sbWaring.setText(data.getData().get流量().getWaringstatus().getValue());
                    clearColor(rbLiuliang);
                    break;
                case R.id.rb_cod:
                    rvParms.setVisibility(View.VISIBLE);
                    dataAdapter.setData(data.getData(), 2);
                    sbTypeOne.setText(data.getData().getCOD().getNowdata().getName());
                    sbNowdata.setText(data.getData().getCOD().getNowdata().getValue());
                    sbTypeTwo.setText(data.getData().getCOD().getDrivestaus().getName());
                    sbStatus.setText(data.getData().getCOD().getDrivestaus().getValue());
                    sbTypeThree.setText(data.getData().getCOD().getWaringstatus().getName());
                    sbWaring.setText(data.getData().getCOD().getWaringstatus().getValue());
                    clearColor(rbCod);
                    break;
                case R.id.rb_andan:
                    rvParms.setVisibility(View.VISIBLE);
                    dataAdapter.setData(data.getData(), 3);
                    sbTypeOne.setText(data.getData().get氨氮().getNowdata().getName());
                    sbNowdata.setText(data.getData().get氨氮().getNowdata().getValue());
                    sbTypeTwo.setText(data.getData().get氨氮().getDrivestaus().getName());
                    sbStatus.setText(data.getData().get氨氮().getDrivestaus().getValue());
                    sbTypeThree.setText(data.getData().get氨氮().getWaringstatus().getName());
                    sbWaring.setText(data.getData().get氨氮().getWaringstatus().getValue());
                    clearColor(rbAndan);
                    break;
                case R.id.rb_ph:
                    rvParms.setVisibility(View.GONE);
                    dataAdapter.setData(data.getData(), 4);
                    sbTypeOne.setText(data.getData().getPH值().getNowdata().getName());
                    sbNowdata.setText(data.getData().getPH值().getNowdata().getValue());
                    sbTypeTwo.setText(data.getData().getPH值().getDrivestaus().getName());
                    sbStatus.setText(data.getData().getPH值().getDrivestaus().getValue());
                    sbTypeThree.setText(data.getData().getPH值().getWaringstatus().getName());
                    sbWaring.setText(data.getData().getPH值().getWaringstatus().getValue());
                    clearColor(rbPh);
                    break;
                case R.id.rb_zongdan:
                    rvParms.setVisibility(View.VISIBLE);
                    dataAdapter.setData(data.getData(), 5);
                    sbTypeOne.setText(data.getData().get总氮().getNowdata().getName());
                    sbNowdata.setText(data.getData().get总氮().getNowdata().getValue());
                    sbTypeTwo.setText(data.getData().get总氮().getDrivestaus().getName());
                    sbStatus.setText(data.getData().get总氮().getDrivestaus().getValue());
                    sbTypeThree.setText(data.getData().get总氮().getWaringstatus().getName());
                    sbWaring.setText(data.getData().get总氮().getWaringstatus().getValue());
                    clearColor(rbZongdan);
                    break;
                case R.id.rb_zonglin:
                    rvParms.setVisibility(View.VISIBLE);
                    dataAdapter.setData(data.getData(), 6);
                    sbTypeOne.setText(data.getData().get总磷().getNowdata().getName());
                    sbNowdata.setText(data.getData().get总磷().getNowdata().getValue());
                    sbTypeTwo.setText(data.getData().get总磷().getDrivestaus().getName());
                    sbStatus.setText(data.getData().get总磷().getDrivestaus().getValue());
                    sbTypeThree.setText(data.getData().get总磷().getWaringstatus().getName());
                    sbWaring.setText(data.getData().get总磷().getWaringstatus().getValue());
                    clearColor(rbZonglin);
                    break;
            }
        }
    }

    private void clearColor(RadioButton rb) {
        rbLiuliang.setTextColor(getResources().getColor(R.color.black));
        rbCod.setTextColor(getResources().getColor(R.color.black));
        rbAndan.setTextColor(getResources().getColor(R.color.black));
        rbPh.setTextColor(getResources().getColor(R.color.black));
        rbZongdan.setTextColor(getResources().getColor(R.color.black));
        rbZonglin.setTextColor(getResources().getColor(R.color.black));
        rb.setTextColor(getResources().getColor(R.color.color_2CA2F4));
    }
}
